<?php
/**
 * 文章内容管理
 * Enter description here ...
 * @author iflamed
 *
 */
class ContentAction extends BaseAction{
	/**
	 * @todo show all content
	 */
	public function index(){
		if(isset($_GET['page'])){
			$nowpage=$_GET['page'];
		}else{
			$nowpage = 1;
		}
		$Content = M('Content');
		$Channel = M('Channel');
		if(isset($_GET['channel']) && intval($_GET['channel'])){
			$this->assign('channel',$_GET['channel']);
			$count = $Content->where('channel_id='.$_GET['channel'])->count();
		}else{
			$this->assign('channel','0');
			$count = $Content->count();
		}
		//每页显示的个数
		$number = 15;
		$count = ceil($count/$number);
		$low = ($nowpage-1) * $number;
		if(isset($_GET['channel']) && intval($_GET['channel'])){
			$contents = $Content->order('content_id desc')->where('channel_id='.$_GET['channel'])->limit($low.','.$number)->select();
		}else{
			$contents = $Content->order('content_id desc')->limit($low.','.$number)->select();
		}
		$channels = $Channel->select();
		$down = $nowpage - 4;
		if($down<1)
		$down = 1;
		$up = $nowpage + 4;
		if($up > $count)
		$up = $count;
		//生成页码表示数组
		$middle = range($down, $up);
		$this->assign('count',$count);
		$this->assign('middle',$middle);
		$this->assign('nowpage',$nowpage);
		$this->assign('contents',$contents);
		$this->assign('channels',$channels);
		$this->display();
	}
	/**
	 * Test add content
	 * Enter description here ...
	 */
	public function newcontent(){
		$Channel = M('Channel');
		$channels = $Channel->select();
		$this->assign('channels',$channels);
		$this->display();
	}
	/**
	 * Add a content
	 */
	public function add(){
		$Content = M("Content");
		$Channel = M("Channel");
		$Playbill = M("Playbill");
		$Content->create();
		$Content->content_text=str_replace(C('WWW'), "/",$Content->content_text);
		$Content->content_time=date('Y-m-d H-i-s');
		$thumb_channelid = $_POST['channel_id'];
		$channelcate = $Channel->where('channel_id='.$Content->channel_id)->find();
		$Content->category_id = $channelcate['channel_category'];
		//参数初始化
		$img ="";$isattach='';$isthumb='';
		//判断是否提取图片首页推荐
		if($Content->content_isthumb == '1'){
			$img = $this->getthumb($Content->content_text);
			if($img == ''){
				$Content->content_isthumb ='0';
			}
		}else{
			$Content->content_isthumb ='0';
		}
		//判断是否有附件
		if ($this->isHaveAttachment($Content->content_text)) {
			$Content->content_attach = 1;
		}else{
			$Content->content_attach = 0;
		}
		$isaddcontent=$Content->add();
		
		//更新首页图片
		if($img != ''){
			$Thumb = M('ContentThumb');
			$thu['thumb_name'] = $img;
			$thu['thumb_content'] = $isaddcontent;
			$thu['thumb_channelid'] = $thumb_channelid;
			$isthumb=$Thumb->data($thu)->add();
		}
		//添加活动宣传图片，大图
		if($_POST['content_bill'] == 1){
			if($img != "")
				$bigimg = $img;
			else 
				$bigimg = $this->getthumb($Content->content_text);
			$bigimage['bill_image'] =str_replace('/thumb_','/', $bigimg);
			$bigimage['bill_show'] = 1;
			$bigimage['bill_content'] = $isaddcontent; 
			if($bigimage['bill_image'] != "")
				$Playbill->data($bigimage)->add();
		}
		$isthumb = $Content->content_isthumb;
		if($isaddcontent || $isthumb || $isattach){
			if($isaddcontent){
				$msg[]='Article';
			}
			if($isattach){
				$msg[]='Attachment';
			}
			if($isthumb){
				$msg[]='ThumbImg';
			}
			//合成输出提示
			$outinfo = implode(',', $msg);
			$this->assign('waitSecond',15);
			$this->assign('jumpUrl','index');
			$this->success('Succeed to add a new '.$outinfo);
		}
	}
        
        protected function isHaveAttachment($sourceHtml){
            return strpos($sourceHtml,'/Uploads/attach/');
        }
        /**
	 * @todo Edit a content
	 */
	public function editcontent(){
		$Channel = M('Channel');
		$channels = $Channel->select();
		$content_id = $_GET['id'];
		$Content = M('Content');
		$acontent=$Content->where('content_id='.$content_id)->find();
		$acontent['content_text']=str_replace("/Public",C('WWW')."Public",$acontent['content_text']);
		$this->assign('acontent',$acontent);
		$this->assign('channels',$channels);
		$this->display();
	}
	/**
	 * update a content
	 */
	public function update(){
		$Content = M('Content');
		$Channel = M('Channel');
		$Playbill = M("Playbill");
		$Content->create();
		$Content->content_text=str_replace(C('WWW'), "/",$Content->content_text);
		$thumb_channelid= $_POST['channel_id'];
		$channelcate = $Channel->where('channel_id='.$Content->channel_id)->find();
		$Content->category_id = $channelcate['channel_category'];
		if($Content->content_isthumb == '1'){
			$img = $this->getthumb($Content->content_text);
			if($img == ''){
				$Content->content_isthumb ='0';
			}
		}else{
			$Content->content_isthumb ='0';
		}
                if ($this->isHaveAttachment($Content->content_text)) {
			$Content->content_attach = 1;
		}else{
			$Content->content_attach = 0;
		}
		$issave = $Content->save();
		//更新首页图片
		$msg= '';
		if($img != ''){
			$Thumb = M('ContentThumb');
			$thu['thumb_name'] = $img;
			$thu['thumb_content'] = $_POST['content_id'];
			$thu['thumb_channelid'] = $thumb_channelid;
			$hasthumb = $Thumb->where("thumb_content=".$thu['thumb_content'])->find();
			if($hasthumb){
				$Thumb->data($thu)->where("thumb_content=".$thu['thumb_content'])->save();
				$msg = ", update a thumb!";
			}else{
				$isthumb=$Thumb->data($thu)->add();
				$msg = ", add a thumb!";
			}
		}else{
			$Thumb = M('ContentThumb');
			$Thumb->where("thumb_content=".$_POST['content_id'])->delete();
			$msg = ", delete a thumb!";
		}
		//添加活动宣传图片，大图
		if($_POST['content_bill'] == 1){
			if($img != "")
				$bigimg = $img;
			else 
				$bigimg = $this->getthumb($Content->content_text);
			$bigimage['bill_image'] =str_replace('/thumb_','/', $bigimg);
			$bigimage['bill_show'] = 1;
			$bigimage['bill_content'] = $thu['thumb_content']; 
			if($bigimage['bill_image'] != "")
				$Playbill->data($bigimage)->add();
		}
		if($issave){
			$this->assign('waitSecond',15);
			$this->assign('jumpUrl','index');
			$this->success('Succeed to update a content'.$msg);
		}else{
			$this->assign('waitSecond',15);
			$this->assign('jumpUrl','index');
			$this->error('Failed to update a content'.$msg);
		}
	}
	/**
	 * @todo Delete a content include thumb and attach
	 */
	public function deletecontent(){
		$contentid= $_GET['id'];
		$conthumb = M('ContentThumb');
		$thumb = $conthumb->where('thumb_content='.$contentid)->delete();
		if($thumb){
			$msg[] = "Delete thumb from database";
		}
		//删除数据库中相册中的图片
		$Contentimage = M('ContentImage');
		$isdeleteimage = $Contentimage->where('image_content_id='.$contentid)->delete();
		if($isdeleteimage)
			$msg[]="Delete albums from database";
		$Attach = M('ContentAttachment');
		$attaches = $Attach->where('content_id='.$contentid)->select();
		$scount = 0;
		$fcount=0;
		foreach ($attaches as $key => $value) {
			$filename = '__APP__/../Public/Uploads/attach/'.$value['attachment_newname'];
			if(is_file($filename)){
				if(unlink($filename))
				$scount = $scount+1;
				else
				$fcount = $fcount+1;
			}else {
				$msg[] = "File not exits";
			}
		}
		//删除数据库中附件的记录
		$Attach->where('content_id='.$contentid)->delete();
		$msg[]="Succeed delete $scount file,$fcount Failed";
		$Content = M('Content');
		//删除数据库中内容的记录
		$isdelete = $Content->where('content_id='.$_GET['id'])->delete();
		if ($isdelete) {
			$msg[]="Delete a content";
			$info = implode(',', $msg);
			$this->assign('waitSecond',15);
			$this->assign('jumpUrl','index');
			$this->success($info);
		}else{
			$msg[]="Failed to delete a content";
			$info = implode(',', $msg);
			$this->assign('waitSecond',15);
			$this->assign('jumpUrl','index');
			$this->success($info);
		}
	}
	/**
	 * @return jsonString
	 * Enter description here ...
	 * @param unknown_type $str
	 */
	protected  function jsonString($str)
	{
		return preg_replace("/([\\\\\/'])/",'\\\$1',$str);
	}
	/**
	 * xheditor文件上传的接收函数
	 * Enter description here ...
	 * @param unknown_type $str
	 */
	public function upload(){
		header('Content-Type: text/html; charset=UTF-8');

		$inputName='filedata';//表单文件域name
		$attachDir='__APP__/../Public/Uploads';//上传文件保存路径，结尾不要带/
		$dirType=1;//1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
		$maxAttachSize=20971520;//最大上传大小，修改为是20M
		$upExt='txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid';//上传扩展名
		$msgType=2;//返回上传参数的格式：1，只返回url，2，返回参数数组
		$immediate=isset($_GET['immediate'])?$_GET['immediate']:0;//立即上传模式，仅为演示用
		ini_set('date.timezone','Asia/Shanghai');//时区

		$err = "";
		$msg = "''";
		$tempPath=$attachDir.'/'.date("YmdHis").mt_rand(10000,99999).'.tmp';
		$localName='';

		if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){//HTML5上传
			file_put_contents($tempPath,file_get_contents("php://input"));
			$localName=$info[2];
		}
		else{//标准表单式上传
			$upfile=@$_FILES[$inputName];
			if(!isset($upfile))$err='文件域的name错误';
			elseif(!empty($upfile['error'])){
				switch($upfile['error'])
				{
					case '1':
						$err = '文件大小超过了php.ini定义的upload_max_filesize值';
						break;
					case '2':
						$err = '文件大小超过了HTML定义的MAX_FILE_SIZE值';
						break;
					case '3':
						$err = '文件上传不完全';
						break;
					case '4':
						$err = '无文件上传';
						break;
					case '6':
						$err = '缺少临时文件夹';
						break;
					case '7':
						$err = '写文件失败';
						break;
					case '8':
						$err = '上传被其它扩展中断';
						break;
					case '999':
					default:
						$err = '无有效错误代码';
				}
			}
			elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')$err = '无文件上传';
			else{
				move_uploaded_file($upfile['tmp_name'],$tempPath);
				$localName=$upfile['name'];
			}
		}

		if($err==''){
			$fileInfo=pathinfo($localName);
			$extension=$fileInfo['extension'];
			if(preg_match('/'.str_replace(',','|',$upExt).'/i',$extension))
			{
				$bytes=filesize($tempPath);
				if($bytes > $maxAttachSize)$err='请不要上传大小超过'.$this->formatBytes($maxAttachSize).'的文件';
				else
				{
					switch($dirType)
					{
						case 1: $attachSubDir = 'day_'.date('ymd'); break;
						case 2: $attachSubDir = 'month_'.date('ym'); break;
						case 3: $attachSubDir = 'ext_'.$extension; break;
					}
					$attachDir = $attachDir.'/'.$attachSubDir;
					if(!is_dir($attachDir))
					{
						@mkdir($attachDir, 0777);
						@fclose(fopen($attachDir.'/index.htm', 'w'));
					}
					PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
					$newFilename=date("YmdHis").mt_rand(1000,9999).'.'.$extension;
					//Change by iflamed
					//$targetPath = $attachDir.'/'.$newFilename;
					$targetPath = 'Public/Uploads/'.$attachSubDir.'/'.$newFilename;
					rename($tempPath,$targetPath);
					@chmod($targetPath,0755);
					$targetPath=$this->jsonString($targetPath);
					if($immediate=='1')$targetPath='!'.C('WWW').$targetPath;
					if($msgType==1)$msg="'$targetPath'";
					else $msg="{'url':'".C('WWW').$targetPath."','localname':'".$this->jsonString($localName)."','id':'1'}";//id参数固定不变，仅供演示，实际项目中可以是数据库ID
				}
			}
			else $err='上传文件扩展名必需为：'.$upExt;

			@unlink($tempPath);
		}

		echo "{'err':'".$this->jsonString($err)."','msg':".$msg."}";
	}
	/**
	 * Resize the picture
	 * Enter description here ...
	 */
	public function uploadimg(){
		header('Content-Type: text/html; charset=UTF-8');

		$inputName='filedata';//表单文件域name
		$attachDir='__APP__/../Public/Uploads';//上传文件保存路径，结尾不要带/
		$dirType=1;//1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
		$maxAttachSize=20971520;//最大上传大小，修改为是20M
		$upExt='txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid';//上传扩展名
		$msgType=2;//返回上传参数的格式：1，只返回url，2，返回参数数组
		$immediate=isset($_GET['immediate'])?$_GET['immediate']:0;//立即上传模式，仅为演示用
		ini_set('date.timezone','Asia/Shanghai');//时区

		$err = "";
		$msg = "''";
		$tempPath=$attachDir.'/'.date("YmdHis").mt_rand(10000,99999).'.tmp';
		$localName='';

		if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){//HTML5上传
			file_put_contents($tempPath,file_get_contents("php://input"));
			$localName=$info[2];
		}
		else{//标准表单式上传
			$upfile=@$_FILES[$inputName];
			if(!isset($upfile))$err='文件域的name错误';
			elseif(!empty($upfile['error'])){
				switch($upfile['error'])
				{
					case '1':
						$err = '文件大小超过了php.ini定义的upload_max_filesize值';
						break;
					case '2':
						$err = '文件大小超过了HTML定义的MAX_FILE_SIZE值';
						break;
					case '3':
						$err = '文件上传不完全';
						break;
					case '4':
						$err = '无文件上传';
						break;
					case '6':
						$err = '缺少临时文件夹';
						break;
					case '7':
						$err = '写文件失败';
						break;
					case '8':
						$err = '上传被其它扩展中断';
						break;
					case '999':
					default:
						$err = '无有效错误代码';
				}
			}
			elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')$err = '无文件上传';
			else{
				move_uploaded_file($upfile['tmp_name'],$tempPath);
				$localName=$upfile['name'];
			}
		}

		if($err==''){
			$fileInfo=pathinfo($localName);
			$extension=$fileInfo['extension'];
			if(preg_match('/'.str_replace(',','|',$upExt).'/i',$extension))
			{
				$bytes=filesize($tempPath);
				if($bytes > $maxAttachSize)$err='请不要上传大小超过'.$this->formatBytes($maxAttachSize).'的文件';
				else
				{
					switch($dirType)
					{
						case 1: $attachSubDir = 'day_'.date('ymd'); break;
						case 2: $attachSubDir = 'month_'.date('ym'); break;
						case 3: $attachSubDir = 'ext_'.$extension; break;
					}
					$attachDir = $attachDir.'/'.$attachSubDir;
					if(!is_dir($attachDir))
					{
						@mkdir($attachDir, 0777);
						@fclose(fopen($attachDir.'/index.htm', 'w'));
					}
					PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
					$newFilename=date("YmdHis").mt_rand(1000,9999).'.'.$extension;
					//Change by iflamed
					//$targetPath = $attachDir.'/'.$newFilename;
					$targetPath = 'Public/Uploads/'.$attachSubDir.'/'.$newFilename;
					rename($tempPath,$targetPath);
					$imgextension = array('jpg','jpeg','gif','png','JPG','JEPG','GIF','PNG');
					if (in_array($extension,$imgextension)) {
					if ($extension == 'jpg' || $extension == "JPG") {
					$img = imagecreatefromjpeg('__APP__/../'.$targetPath);
				}elseif ($extension == 'png' || $extension == "PNG"){
					$img = imagecreatefrompng('__APP__/../'.$targetPath);
				}elseif ($extension == 'gif' || $extension == "GIF"){
					$img = imagecreatefromgif('__APP__/../'.$targetPath);
				}else{
					$img = imagecreatefromwbmp('__APP__/../'.$targetPath);
				}
						$this->ResizeImage($img, 910, 500, '__APP__/../'.$targetPath);
					}
					@chmod($targetPath,0755);
					$targetPath=$this->jsonString($targetPath);
					if($immediate=='1')$targetPath='!'.C('WWW').$targetPath;
					if($msgType==1)$msg="'$targetPath'";
					else $msg="{'url':'".C('WWW').$targetPath."','localname':'".$this->jsonString($localName)."','id':'1'}";//id参数固定不变，仅供演示，实际项目中可以是数据库ID
				}
			}
			else $err='上传文件扩展名必需为：'.$upExt;

			@unlink($tempPath);
		}

		echo "{'err':'".$this->jsonString($err)."','msg':".$msg."}";
	}
	/**
	 * @todo format byte from form.
	 * Enter description here ...
	 * @param unknown_type $bytes
	 */
	protected function formatBytes($bytes) {
		if($bytes >= 1073741824) {
			$bytes = round($bytes / 1073741824 * 100) / 100 . 'GB';
		} elseif($bytes >= 1048576) {
			$bytes = round($bytes / 1048576 * 100) / 100 . 'MB';
		} elseif($bytes >= 1024) {
			$bytes = round($bytes / 1024 * 100) / 100 . 'KB';
		} else {
			$bytes = $bytes . 'Bytes';
		}
		return $bytes;
	}
	/**
	 * Upload file
	 * Enter description here ...
	 */
	protected function _upload() {
		import("@.ORG.UploadFile");
		$upload = new UploadFile();
		//设置上传文件大小
		$upload->maxSize = 32922000;
		//设置上传文件类型
		$upload->allowExts = explode(',', 'txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid');
		//设置附件上传目录
		$upload->savePath = '__APP__/../Public/Uploads/attach/';
		//设置上传文件规则
		$upload->saveRule = 'uniqid';
		//文件同名不覆盖
		$upload->uploadReplace = FALSE;
		//使用子目录方式保存
		$upload->autoSub = TRUE;
		//子目录创建方式DATE
		$upload->subType = 'date';
		if (!$upload->upload()) {
			//捕获上传异常
			$this->error($upload->getErrorMsg());
		} else {
			//取得成功上传的文件信息
			$uploadList = $upload->getUploadFileInfo();
		}
		return $uploadList;
	}
	/**
	 * @todo get the thumbimage from content
	 */
	protected function getthumb($sostr){
		$soImages = '~<img [^\>]*\ />~';
		preg_match_all( $soImages, $sostr, $thePics );
		$allPics = count($thePics[0]);
		switch ( $allPics > 0 ) {
			case $allPics = 1:
				preg_match_all('~(\d+)/(\d+)\.(jpg)?(png)?(gif)?(jpeg)?(JPG)?(PNG)?(GIF)?(JPEG)?~',$thePics[0][0],$newtext);
				$path = $newtext[0][0];
                                $folder = substr($path, 0, 8);
                                list($filename,$extend)=  explode('.', substr($path,9));
                                if($filename=='' || $folder==''){
                                    return '';
                                }
				$oldimage = realpath('./Public/Uploads/'.$path);
				if ($extend == 'jpg' || $extend == "JPG") {
					$img = imagecreatefromjpeg($oldimage);
				}elseif ($extend == 'png' || $extend == "PNG"){
					$img = imagecreatefrompng($oldimage);
				}elseif ($extend == 'gif' || $extend == "GIF"){
					$img = imagecreatefromgif($oldimage);
				}else{
					$img = imagecreatefromwbmp($oldimage);
				}
                                $newimg = './Public/Uploads/'.$folder.'/'.'thumb_'.$filename.'.'.$extend;
				$this->ResizeImage($img, 800, 800,$newimg);
				return $newimg; // 显示文章中的第一张图片
				break; // 当图片数量有1个时，不再执行
			default:
				return ""; // 这里加入没图片时显示的默认图片
				break;
		}
	}
	/**
	 *
	 * Enter description here ...
	 * @param file $im
	 * @param int $maxwidth
	 * @param int $maxheight
	 * @param String $name
	 */
	protected function ResizeImage($im,$maxwidth,$maxheight,$name){
		//取得当前图片大小
		$width = imagesx($im);
		$height = imagesy($im);
		//生成缩略图的大小
		if(($width > $maxwidth) || ($height > $maxheight)){
			$widthratio = $maxwidth/$width;
			$heightratio = $maxheight/$height;
			if($widthratio < $heightratio){
				$ratio = $widthratio;
			}else{
				$ratio = $heightratio;
			}
			$newwidth = $width * $ratio;
			$newheight = $height * $ratio;

			if(function_exists("imagecopyresampled")){
				$newim = imagecreatetruecolor($newwidth, $newheight);
				imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
			}else{
				$newim = imagecreate($newwidth, $newheight);
				imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
			}
			ImageJpeg ($newim,$name);
			ImageDestroy ($newim);
		}else{
			ImageJpeg ($im,$name);
		}
		
	}
}
?>